package com.learn.cloud.validator.code;


import lombok.AllArgsConstructor;
import lombok.Getter;

import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @description: 规则池
 * @author: cong zhi
 * @createDate: 2022/2/6 1:06
 * @updateUser: cong zhi
 * @updateDate: 2022/2/6 1:06
 * @updateRemark: 修改内容
 * @version: v1.0
 */
public class ValidationRulePool {

    @AllArgsConstructor
    @Getter
    private static class Order {
        int order;
        ValidationRuleHandler<Annotation> validationRuleHandler;
    }

    private final static Map<Class<Annotation>, List<Order>> RULES = new ConcurrentHashMap<>();

    public static <T extends Annotation> List<ValidationRuleHandler<T>> getRule(Class<T> annotationClass) {
        List<Order> orders = RULES.get(annotationClass);
        return orders.stream().map(order -> (ValidationRuleHandler<T>) order.getValidationRuleHandler()).collect(Collectors.toList());
    }


    public static void registerRule(Class<Annotation> annotationClass, ValidationRuleHandler<? extends Annotation> validationRuleHandler, int order) {
        List<Order> orders = RULES.computeIfAbsent(annotationClass, k -> new ArrayList<>());
        orders.add(new Order(order, (ValidationRuleHandler<Annotation>) validationRuleHandler));
        orders.sort(Comparator.comparingInt(o -> o.order));
    }
}
